package com.cencat.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cencat.common.dto.BaseDTO;
import com.cencat.common.entity.BaseEntity;
import com.cencat.common.enums.ErrorCode;
import com.cencat.common.exception.BusinessException;
import com.cencat.common.mapper.BaseMapper;
import com.cencat.common.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 基础服务实现类
 * 继承MyBatis-Plus的ServiceImpl，实现BaseService接口
 * 
 * @param <M> Mapper类型
 * @param <T> 实体类型
 * @author cencat
 * @since 2024-01-01
 */

public class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseEntity> 
        extends ServiceImpl<M, T> implements BaseService<T> {

    private static final Logger log = LoggerFactory.getLogger(BaseServiceImpl.class);

    @Override
    public IPage<T> page(BaseDTO dto) {
        try {
            // 参数校验
            if (dto == null) {
                dto = new BaseDTO();
            }
            
            // 创建分页对象
            Page<T> page = new Page<>(dto.getPageNum(), dto.getPageSize());
            
            // 创建查询条件
            QueryWrapper<T> queryWrapper = new QueryWrapper<>();
            
            // 如果是多租户实体，添加租户ID条件
            if (dto.getTenantId() != null) {
                queryWrapper.eq("tenant_id", dto.getTenantId());
            }
            
            // 添加排序条件
            if (dto.getOrderBy() != null && !dto.getOrderBy().trim().isEmpty()) {
                if ("ASC".equalsIgnoreCase(dto.getOrderDirection())) {
                    queryWrapper.orderByAsc(dto.getOrderBy());
                } else {
                    queryWrapper.orderByDesc(dto.getOrderBy());
                }
            }
            
            // 执行分页查询
            IPage<T> result = super.page(page, queryWrapper);
            
            log.debug("根据DTO分页查询实体，当前页: {}，每页数量: {}，总数: {}", 
                    result.getCurrent(), result.getSize(), result.getTotal());
            
            return result;
            
        } catch (Exception e) {
            log.error("根据DTO分页查询实体异常: {}", e.getMessage(), e);
            return new Page<>(1, 10);
        }
    }

    @Override
    public List<T> listByTenantId(Long tenantId) {
        try {
            if (tenantId == null) {
                log.warn("租户ID为空，返回空列表");
                return List.of();
            }
            
            QueryWrapper<T> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("tenant_id", tenantId);
            
            List<T> list = super.list(queryWrapper);
            log.debug("根据租户ID查询实体列表，租户ID: {}，数量: {}", tenantId, list.size());
            
            return list;
            
        } catch (Exception e) {
            log.error("根据租户ID查询实体列表异常: {}", e.getMessage(), e);
            return List.of();
        }
    }

    @Override
    public IPage<T> pageByTenantId(IPage<T> page, Long tenantId) {
        try {
            if (page == null) {
                page = new Page<>(1, 10);
            }
            
            if (tenantId == null) {
                log.warn("租户ID为空，返回空分页结果");
                return new Page<>(page.getCurrent(), page.getSize());
            }
            
            QueryWrapper<T> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("tenant_id", tenantId);
            
            IPage<T> result = super.page(page, queryWrapper);
            
            log.debug("根据租户ID分页查询实体，租户ID: {}，当前页: {}，每页数量: {}，总数: {}", 
                    tenantId, result.getCurrent(), result.getSize(), result.getTotal());
            
            return result;
            
        } catch (Exception e) {
            log.error("根据租户ID分页查询实体异常: {}", e.getMessage(), e);
            return new Page<>(page != null ? page.getCurrent() : 1, 
                           page != null ? page.getSize() : 10);
        }
    }
}